package com.springboot.ww.platform.pd.ctms.demo;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.springboot.ww.platform.pd.ctms.constants.PdApiConstants;
import com.springboot.ww.platform.pd.ctms.service.impl.PdProxyImpl;
import com.springboot.ww.platform.pd.dto.AuthParamValueVO;
import com.springboot.ww.platform.pd.dto.PdStoreTokenVO;
import com.springboot.ww.platform.pd.http.PdHttpProxy;
import com.springboot.ww.platform.pd.http.ResponseMsg;
import com.springboot.ww.platform.pd.util.SignUtil;
import com.ww.springboot.boot.utils.Func;
import com.ww.springboot.boot.utils.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import static cn.hutool.core.util.ClassUtil.isSimpleValueType;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-05-23 16:01
 */
@Slf4j
public class PdddTest {

	private static final String US_URL = "https://openapi-b-us.temu.com/openapi/router";
	private static final String CN_URL = "https://openapi.kuajingmaihuo.com/openapi/router";

	private static final String URL_FORMAT = "https://%s/openapi/router";

	public static void main(String[] args) {
		String ss = "{\n" +
			"            \"authId\": \"1813042287267516417\",\n" +
			"            \"platformCode\": \"PD\",\n" +
			"            \"siteCode\": null,\n" +
			"            \"name\": \"temu-Coora\",\n" +
			"            \"code\": \"pinduoduo_0JTG\",\n" +
			"            \"storeStatus\": 1,\n" +
			"            \"token\": \"upstdwzcthcaamn1g6ydu7oxoxz5rsl1b6ntij0rrg65it5f1cgka5qvmbb\",\n" +
			"            \"paramMap\": {\n" +
			"                \"doMain\": \"openapi-b-global.temu.com\",\n" +
			"                \"appKeyCn\": \"5aafe40503a93de4c2ee8e33f34f31e4\",\n" +
			"                \"tokenCn\": \"ivc0dqeudnngpaaxgjiovmvlz5brn9hymebn81tzxwjnms88kuahzkhd\",\n" +
			"                \"tokenGlobal\": \"upsu9rjz8jqoddpfx9ggehybpt5aepxpftp6j1y941o7ponp5qtkllb45wu\",\n" +
			"                \"currency\": \"USD\",\n" +
			"                \"appSecretCn\": \"00a0b2ca53f47ac7572bd5ce770a4cc10c921aa3\",\n" +
			"                \"appSecret\": \"eb0a027e24acce5cc9c6c7c6e3f61369b7ebe9e4\",\n" +
			"                \"appKey\": \"5c0f9c13c0523766d88355aad9313c7d\"\n" +
			"            },\n" +
			"            \"apiUrl\": \"4.242.79.188\"\n" +
			"        }";
		AuthParamValueVO authParamValueVO = JsonUtil.parse(ss,AuthParamValueVO.class);
		PdStoreTokenVO storeVO = PdStoreTokenVO.builder().apply(authParamValueVO);

		//callShipmentGet(storeVO);
		//shipmentResultGet(storeVO);

		//optimize(storeVO);

		warehouse(storeVO);

		//shipmentGet(storeVO);

		//new PdProxyImpl(null).getUnShipPackageResp(storeVO, null);

		//unShipList(storeVO);


//		String sss = "{\"access_token\":\"ups1a3utzcfmvftnpy762nmsuigsbrpp4vxeov9es6yjooyafblg05wlfpg\",\"app_key\":\"47dbfcc8be49e734c8e91e9231e23128\",\"data_type\":\"JSON\",\"sendRequestList\":[{\"packageSn\":null,\"warehouseId\":\"WH-00845949501591563\",\"weight\":\"0.45\",\"extendWeight\":null,\"extendWeightUnit\":null,\"weightUnit\":\"lb\",\"length\":\"9.45\",\"width\":\"3.25\",\"height\":\"3.25\",\"dimensionUnit\":\"in\",\"channelId\":\"35513654317056\",\"shipCompanyId\":\"960246690\",\"orderSendInfoList\":[{\"parentOrderSn\":\"PO-211-02847348808233877\",\"orderSn\":\"211-02847424829993877\",\"goodsId\":601099648071019,\"skuId\":17592709395886,\"quantity\":1}]}],\"sendType\":\"0\",\"shipLater\":true,\"sign\":\"F3AEF75A5DFCE4F0B9082456B2D5BDBD\",\"timestamp\":1733548255,\"type\":\"bg.logistics.shipment.create\"}";
//		Map<String,Object> map = JsonUtil.toMap(sss);
//		usToken(map, storeVO, "bg.logistics.shipment.create");
//		String resultResp = postUS(storeVO.getApiUrl(), JsonUtil.toJson(map));
//		System.out.println(resultResp);

//		PdShipmentResp.ResultBeanX.ResultBean.ShipmentInfoDTOBean shipmentGet = new PdProxyImpl(null).getShipmentGet(storeVO, new ForecastRecord(), "PO-211-15379693230633960"
//			, "211-15379729930793960");
//		System.out.println(shipmentGet);
//
//		List<PdUnShipPackageResp.ResultDTO.UnshippedPackageDTO> unShipPackageResp = new PdProxyImpl(null).getUnShipPackageResp(storeVO, new ForecastRecord());
//		System.out.println(unShipPackageResp);
	}

	private static void goodPrice(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("productSkuIds", Arrays.asList(7290192361L));
		cnToken(map, storeVO, "bg.goods.price.list.get");
		String s = JsonUtil.toJson(map);
		System.out.println(s);
		String body = HttpRequest.post(CN_URL).body(s).execute().body();
		System.out.println(body);
	}

	private static void unShipList(PdStoreTokenVO storeVO){
		new PdProxyImpl().getUnShipPackageResp(storeVO,"PO-211-21814651126313207",null);
		//new PdProxyImpl(null).getLabelInfo(storeVO,"PO-037-04499091356714014","PK-4649767642071191310",new ForecastRecord());
		//new PdProxyImpl(null).getShipmentGet(storeVO,new ForecastRecord(),"PO-037-04499091356714014","037-04499070385194014");
	}



	private static void getCarrierId(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("regionId", "211");
		usToken(map, storeVO, PdApiConstants.GET_CARRIER_LIST);
		String resultResp = postUS(storeVO.getApiUrl(), JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void price(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("pageSize", 20);
		map.put("page", 0);
		//map.put("skuSearchType", 1);
		map.put("goodsSearchType", 1);
		map.put("searchText", "603080699522795");
		//usToken(map, storeVO, PdApiConstants.GET_GOOD_LIST_US);
		usToken(map, storeVO, "bg.local.goods.list.query");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	/**
	 * 如果能查到标发货信息 就走修改接口
	 */
	private static void shipmentGet(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("parentOrderSn", "PO-211-07771234122793486");
		map.put("orderSn", "211-07771338980393486");
		usToken(map, storeVO, PdApiConstants.SHIPMENT_GET);
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void callShipmentGet(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("pageNumber", "1");
		map.put("pageSize", "50");
		usToken(map, storeVO, "bg.order.unshipped.package.get");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void shipmentResultGet(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("packageSnList", Arrays.asList("PO-211-02847348808233877"));
        usToken(map, storeVO, PdApiConstants.FORECAST_GET);
		String req = JsonUtil.toJson(map);
		String resultResp = postUS(storeVO.getApiUrl(), req);
		System.out.println(resultResp);
	}

	private static void detail(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("parentOrderSn", "PO-211-00998419950713537");

		usToken(map, storeVO, "bg.order.detail.get");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void getLabel(String url, PdStoreTokenVO storeVO) {
		System.out.println(url);
		HttpGet httpGet = new HttpGet(url);
		Map<String, Object> treeMap = new TreeMap<>();
		treeMap.put("toa-app-key", storeVO.getAppKey());
		treeMap.put("toa-access-token", storeVO.getToken());
		treeMap.put("toa-random", Func.md5Hex(UUID.randomUUID().toString()));
		Long time = System.currentTimeMillis() / 1000;
		treeMap.put("toa-timestamp", time);
		// 生成要签名的字符串
		StringBuilder signText = new StringBuilder();
		treeMap.entrySet().forEach(entry -> {
			if (isSimpleValueType(entry.getValue().getClass())) {
				signText.append(entry.getKey()).append(entry.getValue());
			} else {
				signText.append(entry.getKey()).append(JsonUtil.toJson(entry.getValue()));
			}
		});
		String s = storeVO.getAppSecret() + signText + storeVO.getAppSecret();
		for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
			httpGet.setHeader(entry.getKey(), String.valueOf(entry.getValue()));
		}
		httpGet.setHeader("toa-sign", Func.md5Hex(s).toUpperCase());
		//System.out.println(httpGet.getAllHeaders());
		cn.hutool.core.io.FileUtil.writeBytes(PdHttpProxy.proxyByteWithRequest("4.242.79.188", httpGet), "C:\\Users\\ZH500\\桌面\\test\\" + System.currentTimeMillis() + ".png");
	}

	private static void getForecast(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("packageSnList", Arrays.asList("PK-5226980767171271382"));

		usToken(map, storeVO, "bg.logistics.shipment.result.get");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void usToken(Map<String, Object> map, PdStoreTokenVO storeVO, String api) {
		map.put("data_type", "JSON");
		map.put("access_token", storeVO.getToken());
		map.remove("sign");
		String sign = SignUtil.pd(map, storeVO.getAppKey(), storeVO.getAppSecret(), api);
		map.put("sign", sign);
	}


	private static String postUS(String proxyHost, String body) {
		proxyHost = getRealApiUrl(proxyHost);
		HttpPost httpPost = new HttpPost(US_URL);
		StringEntity reqEntity = new StringEntity(body, "UTF-8");
		reqEntity.setContentEncoding("UTF-8");
		reqEntity.setContentType("application/json");
		httpPost.setEntity(reqEntity);
		try {
			ResponseMsg responseMsg = PdHttpProxy.proxyWithRequest(proxyHost, httpPost);
			log.info("拼多多请求：" + body + " | " + JsonUtil.toJson(responseMsg));
			if (responseMsg.getStatus() != 200 || ObjectUtil.isEmpty(responseMsg.getResult())) {
				throw new RuntimeException("拼多多接口调用失败：" + JsonUtil.toJson(responseMsg));
			}
			return responseMsg.getResult();
		} catch (Exception e) {
			log.info("拼多多请求异常：" + body + " | " + e.getMessage());
			throw e;
		}
	}

	private static String getRealApiUrl(String apiUrl) {
		if (ObjectUtil.isEmpty(apiUrl)) {
			return "4.242.79.188";
		}
		int index = apiUrl.lastIndexOf("//");
		if (index < 0) {
			index = 0;
		} else {
			index += 2;
		}
		apiUrl = apiUrl.substring(index);
		return apiUrl;
	}

	private static void good(PdStoreTokenVO storeVO) {
		int page = 1;

		Map<String, Object> map = new TreeMap<>();
		map.put("pageSize", 1);
		map.put("page", page);
		//map.put("goodsSearchType", 1);
//        map.put("createdAtStart", DateUtil.addDate(new Date(),-10).getTime());
//        map.put("createdAtEnd", System.currentTimeMillis());
		//String sign = SignUtil.pd(map, "d0d421fc3ba30209b15f92c8f0eb5c2e", "656cee40abd7b3122f4159b88ecd5c1744502844", PdApiConstants.GET_GOOD_LIST);
		//String sign = SignUtil.pd(map, "d0d421fc3ba30209b15f92c8f0eb5c2e", "656cee40abd7b3122f4159b88ecd5c1744502844", "");
		//usToken(map,storeVO,PdApiConstants.GET_GOOD_LIST);
		cnToken(map, storeVO, PdApiConstants.GET_GOOD_LIST);
		String body = HttpRequest.post(CN_URL).body(JsonUtil.toJson(map)).execute().body();
		page++;
		System.out.println(body);


	}

	private static void goodSku(PdStoreTokenVO storeVO) {
		int page = 0;
		Map<String, Object> map = new TreeMap<>();
		map.put("pageSize", 100);
		map.put("page", page);
		map.put("skuSearchType", 2);
		map.put("searchText", "602629191112478");
//        map.put("createdAtStart", DateUtil.addDate(new Date(),-10).getTime());
//        map.put("createdAtEnd", System.currentTimeMillis());
		//usToken(map, storeVO, PdApiConstants.GET_GOOD_LIST);
		usToken(map, storeVO, "bg.local.goods.sku.list.query");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void warehouse(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		usToken(map, storeVO, "bg.logistics.warehouse.list.get");
		String resultResp = postUS("", JsonUtil.toJson(map));
		System.out.println(resultResp);
	}

	private static void optimize(PdStoreTokenVO storeVO) {

		String ss = "{\"access_token\":\"upsgpbo2fwnhushilwkyaak5qaflkt4h8o5abrottq87hqngvpno6dzqasd\",\"app_key\":\"d8331e6aceb4b43a36a05654cf3eb5ef\",\"data_type\":\"JSON\",\"dimensionUnit\":\"in\",\"height\":\"1.52\",\"length\":\"3.94\",\"orderSnList\":[\"211-03192576046631851\",\"211-03192576046631851\",\"211-03192576046631851\"],\"sign\":\"CA751048FA95C9B9BABE437F5426F0A7\",\"timestamp\":1733541064,\"type\":\"bg.logistics.shippingservices.get\",\"warehouseId\":\"WH-07546107658391233\",\"weight\":\"0.26\",\"weightUnit\":\"lb\",\"width\":\"1.52\"}";


		Map<String, Object> map = JsonUtil.toMap(ss);
//		Map<String, Object> map = new TreeMap<>();
//		map.put("warehouseId", "WH-03111579484310781");
//		map.put("orderSnList", Arrays.asList("211-08709042755111963"));
//		map.put("weight", new BigDecimal("0.30").toString());
//		map.put("weightUnit", "kg");
//		map.put("length", "11.81");
//		map.put("width", "2.16");
//		map.put("height", "2.16");
//		map.put("dimensionUnit", "cm");
		usToken(map, storeVO, "bg.logistics.shippingservices.get");
		String resultResp = postUS(storeVO.getApiUrl(), JsonUtil.toJson(map));
		System.out.println(resultResp);

	}

	private static void getSignCompany(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("regionId", "211");
		usToken(map, storeVO, "bg.logistics.companies.get");
		System.out.println(postUS("", JsonUtil.toJson(map)));
	}

	private static void orderList(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("pageNumber", "1");
		map.put("pageSize", "100");
//        map.put("updateAtStart", DateUtil.addDay(new Date(), -4).getTime() / 1000);
//        map.put("updateAtEnd", DateUtil.addDay(new Date(), -3).getTime() / 1000);
		map.put("data_type", "JSON");
		map.put("parentOrderSnList", JsonUtil.toJson(Arrays.asList("PO-211-01291394939511279")));//最多20个
		usToken(map, storeVO, "bg.order.list.get");
		System.out.println(postUS("", JsonUtil.toJson(map)));
	}

	private static void receiver(PdStoreTokenVO storeVO) {
		Map<String, Object> map = new TreeMap<>();
		map.put("parentOrderSn", "PO-211-20162783155833997");
		usToken(map, storeVO, PdApiConstants.GET_ORDER_RECEIVER);
		System.out.println(postUS("", JsonUtil.toJson(map)));
	}


	private static void cnToken(Map<String, Object> map, PdStoreTokenVO storeVO, String api) {
		map.put("data_type", "JSON");
		map.put("access_token", storeVO.getTokenCn());
		String sign = SignUtil.pd(map, storeVO.getAppKeyCn(), storeVO.getAppSecretCn(), api);
		map.put("sign", sign);
	}
}
